package com.xuanwoa.rabbit.task;

import cn.hutool.core.util.RandomUtil;
import com.xuanwoa.rabbit.constant.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAccumulator;

/**
 * Description
 *
 * @author: xuanwoa
 * @since: 2020/11/27
 */
@Component
@Slf4j
@Profile("send")
public class SendMsgToMQTask {
    private final static LongAccumulator accumulator = new LongAccumulator(Long::sum, 1);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //    @Scheduled(fixedRate = 3000)
    public void sendToDirectExchange() {
        String msg = RandomUtil.randomString(10);
        rabbitTemplate
                .convertAndSend(
                        RabbitConstant.DIRECT_EXCHANGE,
                        "",
                        msg);
        log.info("send direct msg[{}] success", msg);
    }

    //    @Scheduled(fixedRate = 3000)
    public void sendToFanoutExchange() {
        String msg = RandomUtil.randomString(10);
        rabbitTemplate
                .convertAndSend(
                        RabbitConstant.FANOUT_EXCHANGE,
                        "",
                        msg);
        log.info("send fanout msg[{}] success", msg);
    }

    @Scheduled(fixedRate = 1000)
    public void sendToTopicExchange() {
        String routingKey = (accumulator.intValue()) % 2 == 0 ? "topic.d" : "topic.e";
        accumulator.accumulate(1);
        String msg = RandomUtil.randomString(10);
        rabbitTemplate
                .convertAndSend(
                        RabbitConstant.TOPIC_EXCHANGE,
                        routingKey,
                        msg);
        log.info("send topic msg[{}] success - routingKey[{}]", msg, routingKey);
    }
}
